import { NextResponse } from 'next/server'; import { commerceDb } from '@/app/lib/commerce-db'; import { sendEmail } from '@/app/lib/email'; import { env } from '@/app/lib/env'; import { displayOrderId } from '@/app/lib/orders'; import { shippedHtml } from '@/app/lib/order-emails'; import { generateMagicLink } from '@/app/lib/magic-link'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; // CloudEvents v1.0 — Prodigi posts the full order object as `data`. // https://www.prodigi.com/print-api/docs/reference/#webhooks // // Prodigi fires a callback after create, after each shipment is made, // and after the order completes. Crucially, TRACKING arrives on the // "shipment made" callback — and at that point status.stage is usually // still "InProgress" (stage only flips to "Complete" once every shipment // has dispatched). So we react to the presence of a shipment, NOT to // stage alone, or we'd drop the tracking-bearing event. type ProdigiShipment = { status?: string; carrier?: { name?: string; service?: string }; tracking?: { number?: string; url?: string }; }; type ProdigiEvent = { type?: string; id?: string; time?: string; subject?: string; data?: { id?: string; status?: { stage?: string; details?: { shipping?: string } }; shipments?: ProdigiShipment[]; } & Record; }; type Tracking = { number: string | null; url: string | null; carrier: string | null }; // Persist tracking onto the order. Best-effort: the tracking_number / // tracking_url / carrier columns are an additive migration that may not // be applied yet — if they're missing, Postgres errors, we log and move // on. The shipping email (which carries tracking from the event payload) // and the status transition do NOT depend on this succeeding. async function persistTracking( admin: ReturnType, orderId: string, t: Tracking, ): Promise { if (!t.number && !t.url && !t.carrier) return; const { error } = await admin .from('orders') .update({ tracking_number: t.number, tracking_url: t.url, carrier: t.carrier }) .eq('id', orderId); if (error) console.warn('[prodigi] tracking persist skipped (run the columns migration):', error.message); } export async function POST(req: Request, ctx: { params: Promise<{ token: string }> }) { const { token } = await ctx.params; const expected = process.env.PRODIGI_WEBHOOK_TOKEN; if (!expected || token !== expected) return new NextResponse('Not found', { status: 404 }); let event: ProdigiEvent; try { event = (await req.json()) as ProdigiEvent; } catch { return NextResponse.json({ error: 'invalid json' }, { status: 400 }); } const prodigiOrderId = event.subject ?? event.data?.id; console.log('[prodigi] webhook', { type: event.type, id: event.id, prodigiOrderId, time: event.time }); if (!prodigiOrderId) return NextResponse.json({ received: true, ignored: 'no order id' }); const admin = commerceDb(); const { data: order } = await admin .from('orders') .select('id, user_email, status') .eq('prodigi_order_id', prodigiOrderId) .single(); if (!order) { console.warn('[prodigi] no matching order for', prodigiOrderId); return NextResponse.json({ received: true, ignored: 'no matching order' }); } // First shipment that carries any tracking (or is marked Shipped). const shipments = event.data?.shipments ?? []; const shipment = shipments.find( s => s?.tracking?.number || s?.tracking?.url || s?.status === 'Shipped', ); const tracking: Tracking = { number: shipment?.tracking?.number ?? null, url: shipment?.tracking?.url ?? null, carrier: shipment?.carrier?.name ?? null, }; const stage = event.data?.status?.stage; const shippingDone = event.data?.status?.details?.shipping === 'Complete'; const hasShipped = !!shipment || shippingDone || stage === 'Complete'; if (stage === 'Cancelled') { if (order.status !== 'cancelled') { await admin.from('orders').update({ status: 'cancelled' }).eq('id', order.id); } return NextResponse.json({ received: true, status: 'cancelled' }); } if (hasShipped) { // Compare-and-swap on status ALONE (no tracking columns here, so a // pending migration can't block the transition): only one callback // wins the move into `shipped`, so the customer gets exactly one // shipping email even though Prodigi fires the shipment + completed // callbacks (and may retry). Gated to in-flight statuses so we never // resurrect a cancelled order. const { data: claimed } = await admin .from('orders') .update({ status: 'shipped' }) .eq('id', order.id) .in('status', ['approved', 'in_production']) .select('id'); // Persist tracking regardless of who won the race (best-effort). await persistTracking(admin, order.id, tracking); if (claimed && claimed.length > 0) { const link = (await generateMagicLink(order.user_email, `/orders/${order.id}`)) ?? `${env.site.url()}/orders/${order.id}`; await sendEmail({ to: order.user_email, subject: `Your portrait shipped — ${displayOrderId(order.id)}`, html: shippedHtml(order.id, link, tracking), text: `Your portrait shipped${tracking.carrier ? ` via ${tracking.carrier}` : ''}.${tracking.number ? ` Tracking: ${tracking.number}` : ''}${tracking.url ? ` (${tracking.url})` : ''} View your order: ${link}`, }).catch(() => {}); return NextResponse.json({ received: true, newStatus: 'shipped', emailed: true }); } // Already shipped (duplicate/late callback) — never re-send the email. return NextResponse.json({ received: true, idempotent: true }); } // Still in production. if (stage === 'InProgress' && order.status !== 'in_production') { await admin.from('orders').update({ status: 'in_production' }).eq('id', order.id); } return NextResponse.json({ received: true, status: order.status }); }